#include <algorithm>
#include <cctype>
#include "BracketPairHandler.h"
#include "..\..\Common\StringHelper.h"
#include "..\..\Common\AssertHelper.h"

using namespace std;

namespace CExpression
{
	bool BracketPairHandler::ParseCore(ParseContext &context)
	{
		bool ret = false;
		shared_ptr<ExpressionToken> token=context.Tokens()[context.CurrentTokenIndex()];
		if (token->Token == TEXT(")"))
        {
            this->ParseBracketPair(context);
            ret = true;
        }
        return ret;
	}

	void BracketPairHandler::ParseBracketPair(ParseContext &context)
	{
		while(context.OperatorStack().size()>0)
		{
			shared_ptr<ExpressionToken> token=context.OperatorStack().top();
			context.OperatorStack().pop();
			if(token->Token==TEXT("("))
			{
				return;
			}
			else if(token->Token[token->Token.size()-1]==TEXT('('))
			{
				StringHelper::ToLower(token->Token);
				token->Token=TEXT("Function_")+token->Token;
			}
			if(AssertHelper::CreateHandlerExists(token->Token,context,TEXT("Unknow operator/function or missing left bracket.")))
			{
				map<ExpressionString,ExtensionFunction>::iterator iter= ParseContext::extFunctionMap->find(token->Token);
				if(iter!=ParseContext::extFunctionMap->end())
				{
					context.SetCurrentExtFunctionName(token->Token);
				}
				map<ExpressionString,ParseContext::CreateNodeHandlerPtr>::iterator createHandlerIter=ParseContext::createHandlerMap->find(token->Token);
				createHandlerIter->second(context);
				if(StringHelper::StartWith(token->Token,TEXT("Function_")))
				{
					this->PopFunctionParameterCountStack(context);
					return;
				}
			}
		}
		context.SetError();
		context.SetErrorMsg(TEXT("Missing left bracket."));
	}

	void BracketPairHandler::PopFunctionParameterCountStack(ParseContext &context)
	{
		context.FunctionParameterCount().pop();
        context.IncreaseFunctionParameterCount();
	}
}